<template>
    <div>
        <!-- 面包屑 -->
        <el-breadcrumb>
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <el-row style="margin-bottom:15px">
                <el-col :span="4">
                    <el-button type="primary" @click="addRoles">添加角色</el-button>
                </el-col>
            </el-row>
            <!-- 图表 -->
            <el-table :data="rolesLists" stripe border>
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bdbottom',i1 === 0 ? 'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
                            <!-- 一级权限 -->
                            <el-col :span="5">
                                <el-tag>{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 二级权限和三级权限 -->
                            <el-col :span="19">
                                <el-row v-for="(item2,i2) in item1.children" :key="item2.id">
                                    <!-- 二级权限的渲染 -->
                                    <el-col :span="6" :class="[i2 === 0 ? '':'bdtop','vcenter']" >
                                        <el-tag type="success">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag v-for="item3 in item2.children" :key="item3.id" type="warning" closable @close="removeItemListsById(scope.row, item3.id)">{{item3.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                        <pre>
                            {{scope.row}}
                        </pre>
                    </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" icon="el-icon-edit" @click="editRoles(scope.row.id)">编辑</el-button>
                        <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRoles(scope.row.id)">删除</el-button>
                        <el-button size="mini" type="warning" icon="el-icon-setting" @click="settingRoles(scope.row)">分配角色</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 分配角色的对话框 -->
        <el-dialog title="分配角色" :visible.sync="settingRolesDialog"
        width="50%" @close="settingRolesDialogClose">
          <el-tree :data="rolesTreeLists" :props="rolesTreeProps" show-checkbox node-key="id" :default-expand-all="true" :default-checked-keys="dataKey" ref="treeRefs"></el-tree>
          <span slot="footer" class="dialog-footer">
              <el-button @click="settingRolesDialog = false">取 消</el-button>
              <el-button type="primary" @click="allotRights">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 添加角色对话框 -->
        <el-dialog title="添加角色" :visible.sync="addRolesVisibleDialog" width="50%" @close="closeAddRolesDialog">
          <el-form ref="addRoleFormRef" :model="addRoleForm" label-width="80px" :rules="addRolesRules">
            <el-form-item ref="addRolesRef" label="角色名称" prop="roleName">
              <el-input v-model="addRoleForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="addRoleForm.roleDesc"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer">
            <el-button @click="addRolesVisibleDialog = false">取 消</el-button>
            <el-button type="primary" @click="queryAddRoles">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 角色编辑对话框 -->
        <el-dialog
          title="编辑角色"
          :visible.sync="editRolesdialogVisible"
          width="50%" @close="closeEditRolesDialog">
          <el-form ref="editRolesFormRef" :model="editRolesInfos" label-width="80px" :rules="editRolesFormRules">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="editRolesInfos.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="editRolesInfos.roleDesc"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editRolesdialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editRolesdialogVisible = false">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  data () {
    return {
      // 角色列表
      rolesLists: [],
      //   显示和隐藏分配角色对话框
      settingRolesDialog: false,
      //    获取角色树形数据
      rolesTreeLists: [],
      //   树形控件的属性绑定
      rolesTreeProps: {
        label: 'authName',
        children: 'children'
      },
      //   默认选中的Id数据
      dataKey: [],
      //   即将分配角色权限的id
      roleId: '',
      // 显示与隐藏添加角色对话框
      addRolesVisibleDialog: false,
      // 添加角色的表单数据对象
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加roles表单验证
      addRolesRules: {
        roleNmae: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: false, message: '请输入角色的描述内容', trigger: 'blur' },
          { min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' }
        ]
      },
      // 显示和隐藏编辑角色内容
      editRolesdialogVisible: false,
      // 即将要被修改的roles数据内容
      editRolesInfos: {},
      // 修改roles表单验证
      editRolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色的名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: false, message: '请输入角色的描述', trigger: 'blur' },
          { min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async getRolesLists () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表的数据失败')
      }
      this.rolesLists = res.data
    },
    // 根据id删除三级权限列表的数据
    async removeItemListsById (role, rightId) {
      const confirmResult = await this.$messageBox.confirm('此操作将用永久删除此权限？', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户权限失败')
      }
      this.$message({
        type: 'info',
        message: '删除权限信息成功'
      })
      //   刷新页面
      role.children = res.data
    },
    // 分配角色
    async settingRoles (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取分配角色树形数据失败')
      }
      this.rolesTreeLists = res.data

      // 调用递归函数
      this.getLeaFKeys(role, this.dataKey)
      this.settingRolesDialog = true
    },
    // 利用递归函数获取角色下面的三级权限id
    getLeaFKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeaFKeys(item, arr)
      })
    },
    // 关闭分配角色对话框的事件
    settingRolesDialogClose () {
      this.dataKey = []
    },
    // 点击为角色分配权限
    async allotRights () {
      const keys = [
        ...this.$refs.treeRefs.getCheckedKeys(),
        ...this.$refs.treeRefs.getHalfCheckedKeys()
      ]

      const idStr = keys.join(',')

      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限角色失败')
      }
      this.$message.success('分配权限角色成功')
      this.getRolesLists()
      this.settingRolesDialog = false
    },
    // 添加角色
    addRoles () {
      this.addRolesVisibleDialog = true
    },
    // 确定添加角色
    queryAddRoles () {
      this.$refs.addRoleFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')
        this.addRolesVisibleDialog = false
        this.getRolesLists()
      })
    },
    // 查询修改的角色的内容
    async editRoles (id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询角色失败')
      }

      this.editRolesInfos = res.data

      this.editRolesdialogVisible = true
    },
    // 提交编辑的角色
    queryEditRoles () {
      this.$refs.editRolesFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('roles/' + this.editRolesInfos.id, { roleName: this.editRolesInfos.roleName, roleDesc: this.editRolesInfos.roleDesc })
        if (res.meta.status !== 200) {
          return this.$message.error('更新角色信息失败')
        }
        console.log('成功')
        this.$message.success('更新角色信息成功')
        this.getRolesLists()
        this.editRolesdialogVisible = false
      })
    },
    // 删除角色数据
    async deleteRoles (id) {
      const confirmResult = await this.$messageBox.confirm('此操作将用就不删除此角色？', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      }
      this.$message({
        type: 'info',
        message: '删除角色信息成功'
      })
      //   刷新页面
      this.getRolesLists()
    },
    // 关闭添加角色对话框
    closeAddRolesDialog () {
      this.$refs.addRoleFormRef.resetFields()
    },
    // 关闭修改角色对话框
    closeEditRolesDialog () {
      this.$refs.editRolesFormRef.resetFields()
    }
  },
  created () {
    this.getRolesLists()
  }
}
</script>

<style lang="less" scoped>
    .el-tag{
        margin: 10px;
    }
    .bdtop{
        border-top:1px solid #eee ;
    }
    .bdbottom{
        border-bottom:1px solid #eee ;
    }
    .vcenter{
        display: flex;
        align-items: center;
    }
</style>
